package com.thiswhyme.gatewayserver.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.thiswhyme.common.expection.BusinessException;
import com.thiswhyme.common.response.ResponseCode;
import com.thiswhyme.gatewayserver.dto.Constants;
import com.thiswhyme.gatewayserver.utils.JwtHelper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * token拦截器
 * @author thiswhyme 2020/6/1
 */
@Slf4j
@Component
public class TokenFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SERVLET_DETECTION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getHeader(Constants.TOKEN_HEADER);
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(ResponseCode.OPERATION_FAILURE.getCode(), "Token缺失");
        }
        try {
            Claims claims = JwtHelper.validateJwt(token);
            ctx.addZuulRequestHeader(Constants.HEADER_CURRENT_USER, claims.getSubject());
        } catch (BusinessException e) {
            throw new BusinessException(e.getCode(), e.getMsg());
        }
        return null;
    }
}
